using System;
using System.Data;
using System.Text;
using System.Windows.Forms;

using Tino.Controls;
using Tino.Core;

namespace Tino
{
    public class LoadEntryCommand : ICommand
    {
        int entryID;
        TextBox titleTextBox;
        IRtfWritter contentTextBox;
        TextBox tagsTextBox;

        public LoadEntryCommand(int EntryID, TextBox TitleTextBox, IRtfWritter ContentTextBox, TextBox TagsTextBox)
        {
            entryID = EntryID;
            titleTextBox = TitleTextBox;
            contentTextBox = ContentTextBox;
            tagsTextBox = TagsTextBox;;
        }

        #region ICommand Members

        public void Execute()
        {
            Entry entry = new Entry();

            // get the dataset as output
            DataTable dt = entry.GetEntry(entryID);

            if (dt.Rows.Count != 1)
                throw new ApplicationException();

            titleTextBox.Text = (string)dt.Rows[0]["Title"];
            contentTextBox.RtfText = (string)dt.Rows[0]["Content"];

            // Load now the tags
            dt.Dispose();
            dt = entry.GetEntryTags(entryID);

            StringBuilder sb = new StringBuilder();
            int[] tagsIDs = new int[dt.Rows.Count];
            for(int i = 0; i < dt.Rows.Count; i++)
            {
                if (sb.Length > 0) sb.Append("; ");
                sb.Append((string)dt.Rows[i]["Name"]);
                tagsIDs[i] = Convert.ToInt32(dt.Rows[i]["ID"]);
            }

            tagsTextBox.Text = sb.ToString();
            tagsTextBox.Tag = tagsIDs;
        }

        #endregion
    }
}